/**
 * @author KujoMiva
 * @name term.js
 * @time 2020年05月27日 15:50:11 星期三
 */
import {
    getClassifyAPI, addClassifyAPI, putClassifyAPI, delClassifyAPI,
} from "@/api/term";
import { Message } from "element-ui";

export default {
    namespaced: true,
    state: {
        classifyObject: {}, // {type:[{cid:x,name:'xxx'}]}
    },
    mutations: {
        SET_CLASSIFY: (state, { type, data }) => {
            state.classifyObject[type] = data;
        },
        REMOVE_CLASSIFY: (state, type) => {
            delete state.classifyObject[type];
        },
    },
    actions: {
        async getClassifyAction({ state, commit }, type) {
            if (state.classifyObject[type]) return; // 无需重复获取分类列表
            state.classifyObject[type] = [];
            try {
                const { data } = await getClassifyAPI(type);
                commit("SET_CLASSIFY", { type, data });
                return data;
            } catch (error) {
                commit("REMOVE_CLASSIFY", type); // 清除掉旧的分类列表
            }
        },
        async addClassifyAction({ commit, dispatch }, { type, name }) {
            const { code, message } = await addClassifyAPI(type, name);
            if (code !== 200) {
                Message.error(message);
                return;
            }
            commit("REMOVE_CLASSIFY", type); // 清除掉旧的分类列表
            await dispatch("getClassifyAction", type); // 重新获取分类列表
        },
        async putClassifyAction({ commit, dispatch }, { type, cid, name }) {
            const { code, message } = await putClassifyAPI(cid, name);
            if (code !== 200) {
                Message.error(message);
                return false;
            }
            commit("REMOVE_CLASSIFY", type); // 清除掉旧的分类列表
            await dispatch("getClassifyAction", type); // 重新获取分类列表
            return true;
        },
        async delClassifyAction({ commit, dispatch }, { type, cid }) {
            const { code, message } = await delClassifyAPI(cid);
            if (code !== 200) {
                Message.error(message);
                return false;
            }
            commit("REMOVE_CLASSIFY", type); // 清除掉旧的分类列表
            await dispatch("getClassifyAction", type); // 重新获取分类列表
            return true;
        },
    },
};
